package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shop/api/request"
	"shop/initernal/dao"
	"shop/initernal/model"
)

func AddShop(c *gin.Context) {
	var req request.AddShop
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}

	shop := model.Shop{
		Name:  req.Name,
		Intro: req.Intro,
	}
	dao.Create(&shop)

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "新增商品成功",
		"data":    nil,
	})

}
func QueryIdShop(c *gin.Context) {
	var req request.GetInfoIdByShop
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}
	var data model.Shop
	if !dao.GetOneById(req.Id, &data) {
		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "商品查询失败",
			"data":    nil,
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "商品查询成功",
		"data":    data,
	})
}

func UpdateShop(c *gin.Context) {
	var req request.UpdateShop
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}
	var data model.Shop
	if !dao.GetOneByFields(&model.Shop{Name: req.Name}, &data) {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "商品不存在",
			"data":    nil,
		})
		return
	}

	if !dao.Update(&model.Shop{Id: data.Id, Intro: req.Intro}) {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "商品修改失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "商品修改成功",
		"data":    data,
	})
}

func DeleteShop(c *gin.Context) {
	var req request.DeleteShop
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "商品删除成功",
		"data":    nil,
	})

}
